<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>搜索框</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/layer/3.5.1/mobile/need/layer.min.css" />
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        li {
            padding: 10px 0;
            list-style-type: none;
        }

        input {
            outline: 0;
            border-width: 0;
            width: 100%;
        }

        ul {
            margin-top: 10px;
        }

        #box {
            width: 300px;
            margin: 50px auto;
            border: 1px solid #999;
        }
    </style>
</head>

<body>
    <div id="box">
        <input type="text" id="keyword" autocomplete="off" placeholder="请输入关键字" />
        <ul id="list"></ul>
        <script src="./js/axios.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/layer/3.5.1/layer.min.js"></script>
        <script>
            // 获取两个元素
            let inputEle = document.getElementById("keyword");
            let lisEle = document.getElementById("list");
            // 添加内容改变事件 "input"
            inputEle.addEventListener("input", async function () {

                let word = inputEle.value.trim();
                //当搜索框为空时，不发送请求，且清空提示
                if (!word) {
                    lisEle.innerText = "";
                    return;
                };
                //获取后端数据
                let { data } = await axios ({
                    method:"get",
                    url:"http://127.0.0.1:5000/search?word=" + word,   //如果是``反义字符，则可以用模板字符串${ word }
                });
                //当后端的数据为空时，出现提示
                if(data.length === 0){
                    lisEle.innerText = "";
                    layer.msg("暂无搜索结果", { icon: 2 });
                    return;
                };

                let str = "";
                data.forEach((item) => {
                    let { content } = item;
                    str += `<li>${content}</li>`;
                });

                lisEle.innerHTML = str;
            });

        </script>
</body>

</html>